﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using GrainManage.Base;
using GrainManage.Model;
using System.Collections.Generic;
using GrainManage.Tools;
using GrainManage.Entities.Account;
using GrainManage.Proxy;
using System.Windows.Media.Imaging;

namespace GrainManage.Pages
{
    /// <summary>
    /// Interaction logic for LoginPage.xaml
    /// </summary>
    public partial class LoginPage : BasePage
    {
        #region dependency property

        //public static readonly DependencyProperty LoginStateDP;

        //static LoginPage()
        //{

        //    LoginPage.LoginStateDP =
        //        DependencyProperty.Register(
        //            "LoginState",
        //            typeof(string),
        //            typeof(LoginPage),
        //            new FrameworkPropertyMetadata(
        //                null,
        //                FrameworkPropertyMetadataOptions.Journal));
        //}

        //public string LoginState
        //{
        //    get
        //    {
        //        return (string)base.GetValue(LoginPage.LoginStateDP);
        //    }
        //    set
        //    {
        //        base.SetValue(LoginPage.LoginStateDP, value);
        //    }
        //}

        #endregion

        private LoginHelper helper = new LoginHelper();

        public LoginPage()
        {

            InitializeComponent();

            LoadLoginHistory();

            LoadImage();
        }

        //**********************************事件处理函数**********************************
        private void logInButton_Click(object sender, RoutedEventArgs e)
        {
            string userName = comboxUserName.Text.Trim();
            string password = pbPwd.Password.Trim();
            bool remember = (bool)cbRemember.IsChecked;
            string result = string.Empty;

            btnLogin.IsEnabled = false;
            pbFinish.IsEnabled = true;
            pbFinish.Visibility = Visibility.Visible;
            Action tryAction = () =>
            {
                //连接服务器，登录成功后，将用户名添加到列表，供下次使用.
                //连接服务器端进行登录
                InputSignIn input = new InputSignIn
                {
                    UserName = userName,
                    Password = password
                };

                var output = Creator.AccountProxy.SignIn(input);
                if (output != null && output.Status.StatusCode == 1)
                {
                    result = output.Guid;
                    App.Authentication.UserName = userName;
                    App.Authentication.Guid = result;
                    helper.Add(userName, password, remember);
                }
                else
                {
                    SafeInvoke.ShowStatus(output.Status.StatusCode, output.Status.Message, Dispatcher);
                }
            };

            Action finallyAction = () =>
            {
                btnLogin.IsEnabled = true;
                pbFinish.Visibility = Visibility.Hidden;
                pbFinish.IsEnabled = false;
            };

            Action callback = () =>
            {
                if (!string.IsNullOrEmpty(result))
                {
                    NavigateTo(PageUri.MainPage);
                    MainWindow.ResizeMode = ResizeMode.CanResize;
                    MainWindow.Width = 800;
                    MainWindow.Height = 600;
                }
            };

            TryBeginInvoke(tryAction, finallyAction, callback);
        }

        private void btnRemoveClick(object sender, RoutedEventArgs e)
        {
            string user = menuItemDelete.Tag as string;
            if (!string.IsNullOrEmpty(user))
            {
                Action tryAction = () => helper.Remove(user);
                Action callback = () =>
                {
                    menuItemDelete.Tag = null;
                    comboxUserName.ItemsSource = null;
                    comboxUserName.ItemsSource = helper.Users;
                    pbPwd.Password = string.Empty;
                };

                TryBeginInvoke(tryAction, null, callback);
            }
        }

        private void comboxUserName_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock txt = sender as TextBlock;
            menuItemDelete.Tag = (txt != null) ? txt.Text : null;
        }

        private void comboxUserName_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock txt = sender as TextBlock;
            if (txt != null)
            {
                comboxUserName.Text = txt.Text;
                foreach (LoginHistory item in comboxUserName.Items)
                {
                    if (item.UserName.Equals(comboxUserName.Text))
                    {
                        pbPwd.Password = item.Password;
                        cbRemember.IsChecked = item.IsRemember;
                        break;
                    }
                }
            }
        }

        //**********************************辅助函数**********************************
        private void LoadImage()
        {
            Func<Dictionary<string, byte[]>> func = () =>
            {
                var dic = new Dictionary<string, byte[]>();
                var imageProxy = Creator.ImageProxy;
                dic["LoginTitle"] = imageProxy.Download(AppSettings.Get("LoginTitle"));
                dic["LoginBackground"] = imageProxy.Download(AppSettings.Get("LoginBackground"));

                return dic;
            };
            Action<Dictionary<string, byte[]>> callBack = (result) =>
            {
                titleImage.Source = Convertor.ToImage(result["LoginTitle"]);
                backGroundImage.Source = Convertor.ToImage(result["LoginBackground"]);
            };

            TryBeginInvoke(func, callBack);
            //titleImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://m.weather.com.cn/img/b0.gif"));
        }

        private void LoadLoginHistory()
        {
            Action loadAction = () => helper.LoadAll();//加载用户
            Action loadCallback = () => comboxUserName.ItemsSource = helper.Users; //回调函数,更新combox,使其显示加载的用户信息
            TryBeginInvoke(loadAction, null, loadCallback);
        }

        private void LoginPage_Loaded(object sender, RoutedEventArgs e)
        {
            MainWindow = App.Current.MainWindow;
            MainWindow.ResizeMode = ResizeMode.CanMinimize;
            MainWindow.Icon = new System.Windows.Media.Imaging.BitmapImage(GetUri("Images", "corn.jpg"));
            //var weather = Creator.WeatherForecastProxy.GetYahooWeather("shanghai");
        }
    }
}
